package actions;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import utils.Constants;
import utils.MessageViewer;
import utils.ParameterValidator;
import client.ClientSocketConnection;
import client_gui.ClientWindow;


/**
 * Klasa reprezentuje ChangeNick akciju.
 * 
 * @author UrosKrkic & Radivoje Popovic
 */
public class ChangeNickAction extends JButton implements ActionListener, Constants {

	
	/**
	 * Vlasnik akcije.
	 */
	private ClientWindow owner;
	

	/**
	 * Konstruktor.
	 * @param owner - vlasnik akcije
	 * @param label - naziv dugmeta
	 * @author UrosKrkic & Radivoje Popovic
	 */
	public ChangeNickAction(ClientWindow owner) {
		super("Change");
		this.owner = owner;
		
		this.addActionListener(this);
	}
	
	

	public void actionPerformed(ActionEvent e) {
		JPanel panel = new JPanel();
		JLabel label = new JLabel("Nickname:");
	    JTextField nicknameField = new JTextField();
	    nicknameField.setPreferredSize(new Dimension(150,20));
	    
	    panel.add(label);
	    panel.add(nicknameField);
	    
	    int action = JOptionPane.showConfirmDialog(owner, panel, "Enter Nickname", JOptionPane.OK_CANCEL_OPTION);
		
	    if (action != JOptionPane.OK_OPTION) {
	    	return;
	    }
	    
	    String newNickName = nicknameField.getText();
	    
		ParameterValidator.setRegex(ParameterValidator.nicknameRegExp);
		boolean flag = ParameterValidator.matchStrings(newNickName);
		
		if (flag == false) {
			MessageViewer.showError(owner, "Bad or too long Nickname (max. 15 chars.)");
			return;
		}
	    
		ClientSocketConnection connection = owner.getApplicaton().retrieveSocketConnection();
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("CHNICK ");
		buffer.append(owner.getApplicaton().getClientUser().getUsername());
		buffer.append(" ");
		buffer.append(newNickName);
		
		String completedNicknameInfo = buffer.toString();
		
		connection.setMessage(CHNICK_CMD, completedNicknameInfo);
		
		String response;
		
		response = connection.buffers[CHNICK_CMD].read();
		
		if ( response.startsWith("100") ) {
			
			owner.getApplicaton().getClientUser().setNickname(newNickName);
			
			owner.setNickname(newNickName);
		}
		
	}
	
}
